package com.kd.captcha.storage;

import com.kd.captcha.Captcha;
import com.kd.captcha.CaptchaManager;
import com.kd.captcha.config.CaptchaProperties;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.concurrent.TimeUnit;

public class RedisCaptchaStorage implements ICaptchaStorage {

    private final StringRedisTemplate redisTemplate;

    private final CaptchaProperties captchaProperties;

    public RedisCaptchaStorage(StringRedisTemplate redisTemplate, CaptchaProperties captchaProperties) {
        this.redisTemplate = redisTemplate;
        this.captchaProperties = captchaProperties;
    }

    @Override
    public void set(Captcha captcha) {
        this.set(captcha, CaptchaManager.DEF_TIMEOUT, TimeUnit.MINUTES);
    }

    @Override
    public void set(Captcha captcha, long timeout, TimeUnit unit) {
        this.redisTemplate.opsForValue().set(this.getRedisKey(captcha.getName(), captcha.getBiz()), captcha.getValue(), timeout, unit);
    }

    @Override
    public Captcha get(String name, String biz) {
        String value = this.redisTemplate.opsForValue().get(this.getRedisKey(name, biz));

        return new Captcha(name, value, biz);
    }

    @Override
    public boolean remove(Captcha captcha) {
        return this.redisTemplate.delete(this.getRedisKey(captcha.getName(), captcha.getBiz()));
    }

    protected String getRedisKey(String name, String biz) {
        return String.format("captcha:%s:%s:%s", this.captchaProperties.getService(), biz, name);
    }
}
